package com.splashcard.tool.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;



public class MemoryCache extends CacheDataHolderAbstract {
	private static MemoryCache holder = null;
	private HashMap<String, Object> map = null;
	private List<String> tags = null;

	private MemoryCache() {

	}

	public void gc() {
		System.gc();
	}

	public static MemoryCache getInstance() {
		if (holder == null) {
			holder = new MemoryCache();
			holder.map = new HashMap<String, Object>();
			holder.tags = new ArrayList<String>();
		}
		return holder;
	}

	/**
	 * 将一些数据存进内存中
	 */
	@Override
	public int saveData(String tag, Object data) {
		// TODO Auto-generated method stub
		if (data == null) {
			return SAVE_FAILE_OBJECT_NULL;
		}
		if (map.get(tag) != null) {
			map.remove(tag);
			map.put(tag, data);
			return SAVE_SUCCESS_BY_REPLACE;
		} else {
			map.put(tag, data);
			tags.add(tag);
			return SAVE_SUCCESS;
		}
	}

	/**
	 * 获取内存缓存中的数据资源
	 */
	@Override
	public Object getData(String tag) {
		// TODO Auto-generated method stub
		return map.get(tag);
	}

	/**
	 * 清空缓存
	 */
	@Override
	public void cleanCache() {
		// TODO Auto-generated method stub
		map = new HashMap<String, Object>();
		tags = new ArrayList<String>();
	}

	/**
	 * 获取内存中的数据资源，若资源不存在则返回默认值
	 */
	@Override
	public Object getData(String tag, Object Default) {
		// TODO Auto-generated method stub
		Object object = map.get(tag);
		if (object == null) {
			return Default;
		}
		return object;
	}

	/**
	 * 去除内存中的某些数据
	 */
	@Override
	public int remove(String tag) {
		// TODO Auto-generated method stub
		if (map.get(tag) != null) {
			map.remove(tag);
			int index = -1;
			for (int i = 0; i < tags.size(); i++) {
				if (tags.get(i).equals(tag)) {
					index = i;
					break;
				}
			}
			if (index != -1) {
				tags.remove(index);
			}
			return 0;
		} else {
			return 1;
		}
	}

	public void cleanString() {
		for (int i = 0; i < tags.size(); i++) {
			int index = 0;
			while (tags.size() > index) {
				if (map.get(tags.get(index)) instanceof String) {
					map.remove(tags.get(index));
					tags.remove(index);
				} else {
					index++;
				}

			}
		}
	}
}
